<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
            style="float:right"
            type="primary"
            @click="handleSearchList()"
            size="small">
          查询搜索
        </el-button>
        <el-button
            style="float:right;margin-right: 15px"
            @click="handleResetSearch()"
            size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="账号：">
            <el-input v-model="listQuery.username" class="input-width" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="昵称：">
            <el-input v-model="listQuery.nickName" class="input-width" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="手机号码：">
            <el-input v-model="listQuery.phone" class="input-width" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户状态：">
            <el-select v-model="listQuery.flag" style="width:100%">
              <el-option label="无效" value="0"></el-option>
              <el-option label="有效" value="1"></el-option>
            </el-select>
          </el-form-item>

        </el-form>
      </div>
    </el-card>

    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button type="warning" v-if="true" size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px">
        添加
      </el-button>
    </el-card>

    <div class="table-container">
      <el-table ref="roleTable"
                :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>
        <el-table-column label="账号" align="center" prop="username" show-overflow-tooltip/>
        <el-table-column label="昵称" align="center" prop="nickName" show-overflow-tooltip/>
        <el-table-column label="手机号码" align="center" prop="phone" show-overflow-tooltip/>
        <el-table-column label="邮箱" align="center" prop="email" show-overflow-tooltip/>
        <el-table-column label="用户状态" align="center" prop="flag" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.flag == '0'">无效</el-tag>
            <el-tag type="primary" v-if="scope.row.flag == '1'">有效</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip/>
        <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip/>

        <el-table-column label="操作" align="center" width="250" v-if="true || true">
          <template slot-scope="scope">
            <el-button size="mini" v-if="true"
                       type="success"
                       @click="handleSetRole(scope.$index, scope.row)">
              分配角色
            </el-button>
            <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery.current"
          :page-size="listQuery.pageSize"
          :page-sizes="[5,10,15]"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="编辑系统管理-用户基础信息表"
               :visible.sync="editDialogVisible"
               width="80%">
      <el-form :model="user"
               ref="roleForm"
               label-width="150px" size="small">
        <el-form-item label="昵称：">
          <el-input v-model="user.nickName"></el-input>
        </el-form-item>
        <el-form-item label="手机号码：">
          <el-input v-model="user.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：">
          <el-input v-model="user.email"></el-input>
        </el-form-item>
        <el-form-item label="用户状态：">
          <el-select v-model="user.flag" style="width:100%">
            <el-option label="无效" value="0"></el-option>
            <el-option label="有效" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预留防伪信息：">
          <el-input v-model="user.remark"></el-input>
        </el-form-item>
        <el-form-item label="登录密码：">
          <el-input v-model="user.password"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleEditDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="新增系统管理-用户基础信息表"
               :visible.sync="addDialogVisible"
               width="80%">
      <el-form :model="user"
               ref="roleForm"
               label-width="150px" size="small">
        <el-form-item label="账号：">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="登录密码：">
          <el-input v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item label="昵称：">
          <el-input v-model="user.nickName"></el-input>
        </el-form-item>
        <el-form-item label="手机号码：">
          <el-input v-model="user.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：">
          <el-input v-model="user.email"></el-input>
        </el-form-item>
        <el-form-item label="用户状态：">
          <el-select v-model="user.flag" style="width:100%">
            <el-option label="无效" value="0"></el-option>
            <el-option label="有效" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预留防伪信息：">
          <el-input v-model="user.remark"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleAddDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配角色"
               :visible.sync="roleDialogVisible"
               width="60%">
      <el-select
          v-model="currentUserRoles"
          multiple clearable
          filterable
          reserve-keyword
          style="width: 60%"
          placeholder="请选择角色">
        <el-option
            v-for="item in allUserRoles"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>

      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleUpdateRoleByUser()" size="small">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="请选择模板"
               :visible.sync="selectTemplateDialogVisible"
               width="80%">
      <div class="table-container">
        <el-table :data="selectTemplateList"
                  style="width: 100%;"
                  v-loading="selectTemplateListLoading" border>
          <el-table-column label="表名" align="center" prop="tableName" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ allTableNameToDesc[scope.row.tableName] + "-" + scope.row.tableName }}
            </template>
          </el-table-column>
          <el-table-column label="备注信息" align="center" prop="remark" show-overflow-tooltip/>
          <el-table-column label="创建时间" align="center" prop="createTime"/>
          <el-table-column label="更新时间" align="center" prop="updateTime"/>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope">
              <el-upload
                  v-if="selectTemplateListQuery.type == '0'"
                  class="upload-demo"
                  action=""
                  :accept="'.xls, .xlsx'"
                  :limit="1"
                  :before-upload="beforeFileUpload"
                  :http-request="function(file){return handleSelectTemplateUpload(file,scope.row.id);}">
                <el-button size="small" type="primary">点击导入</el-button>
              </el-upload>
              <el-button size="mini" type="primary" @click="handleSelectTemplate(scope.row.id)"
                         v-if="selectTemplateListQuery.type == '1'">选择模板
              </el-button>
              <el-button size="mini" type="warning" @click="handleDownloadTemplate(scope.row.id)"
                         v-if="selectTemplateListQuery.type == '0'">下载模板
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="selectTemplateDialogVisible = false" size="small">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
//导出
import {userDownload, userPostRequire, userPostRequireByConfig} from '@/api/user'
import {sysRolePostRequire} from '@/api/sysRole'
import {sysUserRolePostRequire} from '@/api/sysUserRole'
//all
//导入
import {batchImportExportConfigDownload, batchImportExportConfigPostRequire} from '@/api/batchImportExportConfig'

const defaultListQuery = {
  current: 1,
  pageSize: 10,
  username: undefined,
  nickName: undefined,
  phone: undefined,
  flag: undefined,

}
const defaultUser = {
  id: undefined,
  username: undefined,
  password: undefined,
  nickName: undefined,
  phone: undefined,
  email: undefined,
  flag: undefined,
  openId: undefined,
  remark: undefined,
  createTime: undefined,
  updateTime: undefined,

}
export default {
  name: 'userList',
  data() {
    return {
      listQuery: this.$deepClone( defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      addDialogVisible: false,
      editDialogVisible: false,
      roleDialogVisible: false,
      user: this.$deepClone( defaultUser),
      allUserRoles: [],
      currentUserRoles: [],
      currentUserId: '',

      //all
      selectTemplateList: [],
      selectTemplateDialogVisible: false,
      selectTemplateListLoading: false,
      selectTemplateListQuery: {
        current: 1,
        pageSize: 10,
        tableName: "user",
        type: undefined,
      },

    }
  },
  created() {
    if(this.$route.query){
      let keys = Object.keys(this.$route.query)
      if (keys.length > 0){
        keys.forEach(k=>{
          this.listQuery[k] = this.$route.query[k]
        })
      }
    }
    this.getList()
    this.getAllRoles()
    //all
    this.getAllTableInfo()
  },
  methods: {
    //all
    getAllTableInfo() {
      this.listLoading = true
      batchImportExportConfigPostRequire('getAllTableInfo').then(response => {
        this.listLoading = false
        this.allTableNameToDesc = response.data || {}
      })
    },
    //导出
    handleBatchExport() {
      this.selectTemplateListQuery.type = '1'
      this.selectTemplateListLoading = true
      this.selectTemplateDialogVisible = true
      this.selectTemplateList = []
      batchImportExportConfigPostRequire('listPage', this.selectTemplateListQuery).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        this.selectTemplateListLoading = false
        this.selectTemplateList = response.data.records
      })
    },
    handleSelectTemplate(configId) {
      let thisListQuery = JSON.parse(JSON.stringify(this.listQuery));
      thisListQuery.exportConfigId = configId
      userDownload('batchExport', thisListQuery).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
      })
    },
    beforeFileUpload(file) {
      const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isExcel) {
        this.$message.error('上传文件只能是 xls/xlsx 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!');
      }
      return isExcel && isLt5M;
    },
    //导入
    handleSelectTemplateUpload(file, importConfigId) {
      let params = new FormData()
      params.append("xlsFile", file.file);
      params.append("importConfigId", importConfigId);
      let headers = {
        'Content-Type': 'multipart/form-data; name="xlsFile"'
      }
      userPostRequireByConfig('batchImport', params, headers).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        this.selectTemplateDialogVisible = false
      }).finally(() => {
        this.getList()
      })
    },
    handleBatchImport() {
      this.selectTemplateListQuery.type = '0'
      this.selectTemplateListLoading = true
      this.selectTemplateDialogVisible = true
      this.selectTemplateList = []
      batchImportExportConfigPostRequire('listPage', this.selectTemplateListQuery).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        this.selectTemplateListLoading = false
        this.selectTemplateList = response.data.records
      })
    },
    handleDownloadTemplate(configId) {
      batchImportExportConfigDownload("getImportExcel", {exportConfigId: configId}).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
      })
    },

    handleResetSearch() {
      this.listQuery = this.$deepClone( defaultListQuery)
    },
    handleSearchList() {
      this.listQuery.current = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.current = 1
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.current = val
      this.getList()
    },
    handleAdd() {
      this.addDialogVisible = true
      this.user = this.$deepClone( defaultUser)
    },
    handleDelete(row) {
      this.$confirm('是否要删除该系统管理-用户基础信息表?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userPostRequire('delete', {'id': row.id}).then(response => {
          if (response) {
            this.$message({
              message: response.message,
              type: response.status ? 'success' : 'error'
            })
          }
        }).finally(() => {
          this.getList()
        })
      })
    },
    handleSetRole(index, row) {
      this.currentUserId = row.id
      sysUserRolePostRequire('getRoleByUser', {userId: row.id}).then(response => {
        this.currentUserRoles = response.data || []
        this.roleDialogVisible = true
      })
    },
    handleUpdateRoleByUser() {
      sysUserRolePostRequire('updateRoleByUser', {
        userId: this.currentUserId,
        roleIds: this.currentUserRoles.toString()
      }).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: 'success'
          })
        }
        this.roleDialogVisible = false
      })
    },
    handleUpdate(row) {
      this.editDialogVisible = true
      this.user = this.$deepClone( row)
    },
    handleEditDialogConfirm() {
      userPostRequire('update', this.user).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        this.editDialogVisible = false
      }).finally(() => {
        this.getList()
      })
    },
    handleAddDialogConfirm() {
      userPostRequire('add', this.user).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        this.addDialogVisible = false
      }).finally(() => {
        this.getList()
      })
    },
    getList() {
      this.listLoading = true
      userPostRequire('listPage', this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data.records
        this.total = response.data.total
      })
    },
    getAllRoles() {
      sysRolePostRequire('listPage', {current: 1, pageSize: 100}).then(response => {
        let arr = response.data.records || []
        let allUserRoles = []
        for (let i = 0; i < arr.length; i++) {
          let role = arr[i]
          allUserRoles.push({label: role.name, value: role.id})
        }
        this.allUserRoles = allUserRoles
      })
    }
  }
}
</script>
<style></style>
